package com.zerlings.gabeisfaker.ui.inventory

import android.media.AudioManager
import android.media.SoundPool
import android.os.Build
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import com.zerlings.gabeisfaker.BR
import com.zerlings.gabeisfaker.MyApplication.Companion.context
import com.zerlings.gabeisfaker.R
import com.zerlings.gabeisfaker.data.model.UniqueItem
import com.zerlings.gabeisfaker.data.repository.ItemRepository
import com.zerlings.gabeisfaker.ui.BaseViewModel
import com.zerlings.gabeisfaker.ui.MainActivity
import com.zerlings.gabeisfaker.util.initGun
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashSet

class InventoryViewModel : BaseViewModel() {

    private val itemRepository = ItemRepository

    private val uniqueItemList: ArrayList<UniqueItem>  = itemRepository.getUniqueItems()

    private val soundPool: SoundPool = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        SoundPool.Builder().build()
    } else {
        SoundPool(2, AudioManager.STREAM_MUSIC, 5)
    }

    private val soundId = soundPool.load(context, R.raw.display, 1)

    private val specificList = ArrayList(uniqueItemList)

    val title: String = context.getString(R.string.inventory)

    val positionSet = HashSet<Int>()

    val adapter = InventoryAdapter(BR.uniqueItem, R.layout.skin_item, specificList, positionSet)

    val singleMode = MutableLiveData(false)

    val multiMode = MutableLiveData(false)

    val upperItem = MutableLiveData<UniqueItem>()

    private var currentLevel = 0

    private lateinit var seedItem: UniqueItem

    lateinit var uniqueItem: UniqueItem

    /**删除选中物品*/
    fun deleteItem() {
        val uniqueItems = ArrayList(specificList)
        var randomIndex = Random().nextInt(positionSet.size)
        var wearSum = 0f
        positionSet.forEach {
            val weapon = uniqueItems[it]
            val newPosition = specificList.indexOf(weapon)
            specificList.removeAt(newPosition)
            adapter.notifyItemRemoved(newPosition)
            adapter.notifyItemRangeChanged(newPosition, specificList.size - newPosition)
            uniqueItemList.remove(weapon)
            wearSum += weapon.wearValue
            if (randomIndex-- == 0) {
                seedItem = weapon
            }
            itemRepository.deleteItem(weapon)
        }
        seedItem.wearValue = wearSum / positionSet.size
        positionSet.clear()
        multiMode.value = false
    }

    /**单选逻辑*/
    fun itemClick(position: Int) {
        if (multiMode.value!!) {
            /*如果当前处于多选状态，则进入多选状态的逻辑*/
            when {
                positionSet.contains(position) -> positionSet.remove(position)// 如果包含，则撤销选择
                !positionSet.contains(position) && positionSet.size < 10 -> {
                    positionSet.add(position)
                    uniqueItem = specificList[position]
                }// 如果不包含，则添加
                else -> {}
            }
            if (positionSet.isEmpty()) {
                multiMode.value = false// 如果没有选中任何的item，则退出多选模式
            }
        } else {
            /*如果不是多选状态，则进入单选事件的业务逻辑*/
            uniqueItem = specificList[position]
            if (positionSet.contains(position)) {
                singleMode.value = false
                positionSet.remove(position)// 如果包含，则撤销选择
            } else {
                singleMode.value = true
                positionSet.clear()// 选择不同的单位时取消之前选中的单位
                positionSet.add(position)// 如果不包含，则添加
            }
        }
    }

    /**多选逻辑*/
    fun itemLongClick() {
        if (!multiMode.value!!) {
            multiMode.value = true
            singleMode.value = false
            positionSet.clear()
        }
    }

    /**筛选特定列表*/
    fun setSpecificList(level: Int) {
        currentLevel = level
        specificList.clear()
        if (level == MainActivity.LEVEL_ALL) {
            specificList.addAll(uniqueItemList)
        }else {
            uniqueItemList.forEach {
                if (it.quality == level) {
                    specificList.add(it)
                }
            }
        }
    }

    /**检查汰换条件*/
    fun tradeUpCheck(): Boolean {
        val correctList = tradeListCheck()
        return when {
            positionSet.size == 10 && correctList && uniqueItem.quality < MainActivity.LEVEL_CONVERT -> true
            positionSet.size < 10 -> {
                Toast.makeText(context, R.string.insufficient_material, Toast.LENGTH_SHORT).show()
                false
            }
            !correctList -> {
                Toast.makeText(context, R.string.incorrect_list, Toast.LENGTH_SHORT).show()
                false
            }
            uniqueItem.quality >= MainActivity.LEVEL_CONVERT -> {
                Toast.makeText(context, R.string.wrong_level, Toast.LENGTH_SHORT).show()
                false
            }
            else -> false
        }
    }

    /**检查列表是否一致*/
    private fun tradeListCheck(): Boolean {
        positionSet.forEach {
            if (specificList[it].isStatTrak != uniqueItem.isStatTrak || specificList[it].quality != uniqueItem.quality) {
                return false
            }
        }
        return true
    }

    /**计算汰换合同物品*/
    fun tradeUpItem() {
        deleteItem()
        val upperList = initGun(seedItem.caseName).filter { it.quality == seedItem.quality + 1 }
        var targetWear: Float
        upperItem.value = UniqueItem(upperList[Random().nextInt(upperList.size)].apply {
            isStatTrak = uniqueItem.isStatTrak
            targetWear = (maxWear - minWear) * seedItem.wearValue / 100 + minWear
        }, targetWear)
        soundPool.play(soundId,1f, 1f, 5, 0, 1f)
    }

    /**取消选中*/
    fun cancelSelect() {
        multiMode.value = false
        singleMode.value = false
        positionSet.clear()
    }

    /**保存物品*/
    fun saveItem() {
        itemRepository.saveItem(upperItem.value!!)
        uniqueItemList.add(upperItem.value!!)
        if (currentLevel == MainActivity.LEVEL_ALL) {
            specificList.add(upperItem.value!!)
        }
    }
}
